﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace ChatRoomServer
{
    public partial class FormChatRoomServer : Form
    {
        TcpListener listenerSocket = new TcpListener(IPAddress.Any, 8888);
        List<TcpClient> clientSockets = new List<TcpClient>();
        Thread threadAccept;
        Thread threadReceive;
        byte[] receiveByte=new byte[1024];

        public FormChatRoomServer()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            listenerSocket.Start();
            threadAccept = new Thread(new ThreadStart(AcceptThread));
            threadAccept.Start();
            base.OnLoad(e);
        }
        public void AcceptThread() 
        {
            while (true)
            {
                TcpClient clientSocket = listenerSocket.AcceptTcpClient();
                clientSockets.Add(clientSocket);
                threadReceive = new Thread(new ParameterizedThreadStart(ReceiveThread));
                threadReceive.Start(clientSocket);
            }
        }
        void ReceiveThread(object parameter) 
        {
            TcpClient clientSocket = parameter as TcpClient;
            while (true)
            {
                NetworkStream netStream = clientSocket.GetStream();
                int len = netStream.Read(receiveByte, 0, receiveByte.Length);
                string message = Encoding.Default.GetString(receiveByte, 0, len);
                string[] NameAndMessage = message.Split(':');
                Invoke(new AddClientCallBack(AddClient), new object[] { NameAndMessage[0]});
                foreach (TcpClient s in clientSockets)
                {
                    NetworkStream nsClient = s.GetStream();
                    nsClient.Write(receiveByte, 0, len);
                }
            }
        }
        delegate void AddContextDelegage(string text);
        public void AddContext(string text) 
        {
            rTBChat.AppendText(text + "\n");
        }
        delegate void AddClientCallBack(string name);
        public void AddClient(string name)
        {
            if (!lBClient.Items.Contains(name))
            {
                lBClient.Items.Add(name);
            }
        }
    }
}
